//
// Copyright (c) 2014, 保留所有权利。
//
// ContractSync.java
//
// 作    者：王红燕
// 当前版本：1.0
// 2014 下午1:16:13
//
// 
//
package com.vanke.agent.sync;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;

import org.apache.log4j.Logger;

import com.vanke.agent.ADataSource;
import com.vanke.agent.C;
import com.vanke.agent.Cfg;
import com.vanke.agent.bean.FlagLogBean;
import com.vanke.agent.common.CstUtil;
import com.vanke.agent.common.FlagLog;
import com.vanke.agent.common.FollowRecordUtil;
import com.vanke.agent.common.GUIDCacheChecker;
import com.vanke.agent.common.RecommendUtil;
import com.vanke.agent.common.TradeUtil;
import com.vanke.agent.common.Util;
import com.vanke.agent.common.log.LoggerUtil;

/**
 *
 */
public class ReceiveSync extends AgentSync {
	Logger log = LoggerUtil.getLoggerByName("receive_sync");
	String table = "s_CstReceive";
	String fields = C.FIELDS_RECEIVE;

	@Override
	public void sync() {
		log.info("=============sync new Receive===========");
		Connection con = ADataSource.getConnection(ADataSource.SCHEMA_MY);
		Connection wcon = ADataSource.getConnection(ADataSource.SCHEMA_BIZ);
		GUIDCacheChecker.loadReceiveGuidCache();
		try {

			//			String timeStr = dateFormat.format(receiveCfg.beginTime);
			String timeStr = dateFormat.format(Util.offMinute(
					receiveCfg.beginTime, rebackOffset));
			//			receiveCfg.beginTime = new Date(System.currentTimeMillis());
			String nowStr = dateFormat.format(new Date(System
					.currentTimeMillis()));

			String querySql = "SELECT " + fields + "  FROM " + table;
			querySql += " where CreatonDate > ? and CreatonDate < ? "
					+ " order by CreatonDate asc";
			log.info("execute: " + querySql + "[" + timeStr + "~" + nowStr
					+ "]");

			String insertfields = fields
					+ ",ProjGUID,OriCstGUID,ProjCode,followType,SrcType,RecommendGUID";

			String[] fs = fields.split(",");
			int columns = fs.length;

			PreparedStatement pstmt = con.prepareStatement(querySql,
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY);
			pstmt.setString(1, timeStr);
			pstmt.setString(2, nowStr);

			ResultSet rs = pstmt.executeQuery();
			if (!rs.next()) {
				log.info("no Receive is created");
				ADataSource.close(rs);
				ADataSource.close(pstmt);
				return;
			}
			int count = 0, record = 0;
			do {
				record++;
				receiveCfg.beginTime = new Date(rs.getTimestamp("CreatonDate")
						.getTime());
				String myguid = rs.getString("MyGUID");
				if (myguid == null || myguid.length() < 2) {
					continue;
				}
				Timestamp time = rs.getTimestamp("ReceiveDate");
				int check = GUIDCacheChecker.existsMyGUID(myguid);
				// 判断是否已存在
				switch (check) {
				case GUIDCacheChecker.CHECK_SAME:
				case GUIDCacheChecker.CHECK_EXIST:
					log.info("ignore aready handled receive:" + myguid);
					continue;
				case GUIDCacheChecker.CHECK_NOT_EXIST:
					//GUIDCacheChecker.saveMYGUID(myguid, time);
					break;
				} // 
				
				String projGUID = null;
				String projCode = null;

				String oriCstGUID = rs.getString("CstGUID");
				if (oriCstGUID == null) {
					GUIDCacheChecker.saveMYGUID(myguid, time);
					continue;
				}
				long uid = CstUtil.getCstGUIDByOriGuid(wcon, oriCstGUID);
				if (uid == 0) {
					log.info("receive no CstGUID found for:" + oriCstGUID
							+ ", retrieve again");
					uid = CstUtil.retrieveMemship(oriCstGUID);
				}
				
				if (uid == 0) { // 反查仍未关联到客户，关联同到的本条记录不同步
					log.info("in dc no CstGUID found for:" + oriCstGUID);
					continue;
				}
				// 本次处理，保存映射
				GUIDCacheChecker.saveMYGUID(myguid, time);

				String tb = CstUtil.retrieveCstReceiveTable(uid);
				String insertSql = CstUtil.formatInsertSql(tb, insertfields);
				PreparedStatement wpstmt = wcon.prepareStatement(insertSql);

				for (int i = 1; i <= columns; i++) {
					if (fs[i - 1].equals("CreatonDate")) {
						wpstmt.setTimestamp(i,
								new Timestamp(System.currentTimeMillis()));
					} else {
						wpstmt.setString(i, rs.getString(i));
					}
				}

				wpstmt.setLong(7, uid);

				String sql = "select ProjGUID from s_Opportunity where OppGUID = ?";
				PreparedStatement proPs = con.prepareStatement(sql,
						ResultSet.TYPE_SCROLL_INSENSITIVE,
						ResultSet.CONCUR_READ_ONLY);
				proPs.setString(1, rs.getString("OppGUID"));
				ResultSet proRs = proPs.executeQuery();

				if (proRs.next()) {
					projGUID = proRs.getString("ProjGUID");
				}
				wpstmt.setString(11, projGUID);
				wpstmt.setString(12, oriCstGUID);
				projCode = getProjectCode(con, projGUID);
				wpstmt.setString(13, projCode);
				String recvType = rs.getString("ReceiveType");
				int followType = FollowRecordUtil.getFollowType(recvType);
				wpstmt.setInt(14, followType); // followType
				wpstmt.setString(15, "my"); // SrcType
				//RecommendGUID,cstStatus,tradeGUID,amount,tradeStatusTrack,tradeStatus,lastVisitDate
				String[] recommend= RecommendUtil.getAgentCstRecommed(con,
						uid, projCode);
				wpstmt.setString(16, recommend == null ? "" : recommend[0]); // recommendGUID
				// 4）明源：上门 == 到访 3
				// 1）明源：来访 == 到访 3
				// 2）明源：其它/其他 == 其他 8
				// 3）明源：去电/来电 == 来电 2
				// 5）明源：转机会 == 9
				// 6）明源：空 == 0 不处理， 因为只有8条数据，都是2010年的
				String info = "[cstGUID=" + uid + ",OriGUID=" + oriCstGUID
						+ ",ProjCode=" + projCode + ",ReceiveType=" + recvType
						+ ",followType=" + followType + "]";
				log.info("follow record saved:" + info);
				try {
					wpstmt.executeUpdate();
					//更新售前客户状态
					if(recommend!=null){
						if((followType==2||followType==3) && followType>=Integer.valueOf(recommend[1])){
						RecommendUtil.updateCstStatusForFollow(wcon, uid, recommend[0], recommend[1], followType, time
								,Long.valueOf((recommend[6]==null)?"0":recommend[6].trim()));
					    info = "[cstGUID=" + uid + ",recommendGUID=" + recommend[0]
						+",followType=" + followType + "]";
						log.info("update cstStatus:"+info);
						}
					}else{
						log.info("follow record recommend not exist:" + info);
					}
					count++;
				} catch (Exception e) {
					e.printStackTrace();
					log.error(e);
				} finally {
					ADataSource.close(proRs);
					ADataSource.close(proPs);
					ADataSource.close(wpstmt);
				}
				// 通知
				//				sendNotice(uid, projCode, followType, time);
				String recommendGUID = recommend == null ? "" : recommend[0];
				if (uid != 0) {
					FlagLogBean flb = new FlagLogBean();
					flb.setAppid(C.DC_APPID);
					flb.setCstGUID(uid);
					flb.setOriCstGUID(oriCstGUID);
					flb.setProjCode(projCode);
					// String ReceiveType,                  //	跟进类型，明源中的文字
					flb.setFlag(followType);
					flb.setFlagTime(time);
					flb.setComment("");
					flb.setRoomGUID("");
					flb.setRecommendGUID(recommendGUID);
					// private String SubStatus;		// 子状态，即每一个Flag对应的自有状态,
					// private String UserGUID; 		// 置业顾问题,
					flb.setPrmAgent(rs.getString("UserGUID"));
					flb.setRefGUID(myguid);
					FlagLog.saveFlagLog(flb);

					TradeUtil.sendNotice(C.NOTICE_FOLLOW, uid, projCode, time,
							0, followType, recvType, C.TRADE_STATUS_NONE, null, null, null);
				} // end if
			} while (rs.next());

			// 保存配置，最后一次的时间
			Cfg.set(receiveCfg.cfgKey,
					dateFormat.format(receiveCfg.beginTime));
			Cfg.save();

			// 关闭
			ADataSource.close(rs);
			ADataSource.close(pstmt);

			log.info(count + " Receive synced by " + record + " records");
			log.info("=============sync Receive end===========");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ADataSource.close(con);
			ADataSource.close(wcon);
			GUIDCacheChecker.releaseReceive();
		}
	} // ~sync
}
